
const HID = require('node-hid');
const usbDetect = require('usb-detection');

///启动监听USB插拔
function startHIDMonitoring() {
    usbDetect.startMonitoring();

    usbDetect.on('add', device => {
        if (device.vendorId === vendorId && device.productId === productId) {
            console.log('HID 设备已插入，尝试连接...');
            openHID();
        }
    });

    usbDetect.on('remove', device => {
        if (device.vendorId === vendorId && device.productId === productId) {
            console.log('HID 设备已移除，断开连接');
            closeHID();
        }
    });
}

// 获取HID所有设备
async function HIDList() {
    const devices = HID.devices();
    console.log('===== HID Devices List =====');
    console.log(devices);
    return devices;
}

//拿到指定的HID设备，并且打开
async function openHID(_) {
    const devices = HID.devices();
    try {
        const deviceInfo = devices.find(d => d.vendorId === vendorId && d.productId === productId && d.interface === interfaceId);
        if (!deviceInfo) {
            mainWindow.webContents.send('hid-status', { connected: false, msg: '未找到指定 HID 设备' });
            throw new Error('未找到指定 HID 设备');
        }
        hid_device = new HID.HID(deviceInfo.path);
        console.log(`已连接到 HID 设备 === ${deviceInfo}`);
        mainWindow.webContents.send('hid-status', { connected: true, msg: '已连接到 HID 设备' });

        ///接收数据
        hid_device.on('data', (data) => {
            // 如需将 Buffer 转 HEX
            console.log('HEX:', data.toString('hex'));
        });

        // 错误监听
        hid_device.on('error', (err) => {
            console.error('设备错误:', err);
        });
        return hid_device;
    } catch (error) {
        console.error('获取指定HID设备错误', error);
        mainWindow.webContents.send('hid-status', { connected: false, msg: `${error}` });
        return null;
    }
}

///关闭hid
function closeHID() {
    if (hid_device) {
        try {
            hid_device.close();
            console.log('已断开 HID 设备连接');
            mainWindow.webContents.send('hid-status', { connected: false, msg: '已断开 HID 设备连接' });
        } catch (e) {
            console.error('断开 HID 设备出错:', e);
        }
        hid_device = null;
    }
}

// 发送数据
function sendData(_, data) {
    const reportId = 0x00;
    let payload = Uint8Array.from(data); // 要发送的字节
    const bytes = [reportId, ...payload];
    try {
        const bytesWritten = hid_device.write(bytes);
        console.log(`已发送 ${bytesWritten} 字节:`, bytes);
    } catch (err) {
        console.error('发送数据时出错:', err);
    }
}

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
        closeHID();
    }
});

// 程序退出时停止监听
process.on('exit', () => {
    usbDetect.stopMonitoring();
    closeHID();
});